import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 独立完成注册功能,要求如下:
 * 1.使用预编译SQL
 *
 * 结果:
 *   1.用户名被占用
 *   2.恭喜,注册成功
 * SQL语句:
 *   1.String sql1 = "SELECT id FROM tedu.userinfo WHERE username=?"
 *   2.String sql2 = "INSERT INTO tedu.userinfo(username,password,nickname,age) VALUES(?,?,?,?)"
 * 注意:
 *   创建2个预编译SQL执行对象,比如: ps1 和 ps2
 */

public class JDBCReg {
    public static void main(String[] args) {
        // 接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("注册功能");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        System.out.println("请输入昵称:");
        String nickname = scanner.nextLine();
        System.out.println("请输入年龄:");
        int age = scanner.nextInt();

        try (Connection connection = DBUtil.getConnection();){
            // 确认用户名是否被占用
            String sql1 = "SELECT id FROM tedu.userinfo WHERE username=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, username);
            ResultSet resultSet = ps1.executeQuery();

            if (resultSet.next()){
                System.out.println("用户名被占用");
            }else{
                // 执行注册流程
                String sql2 = "INSERT INTO tedu.userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1, username);
                ps2.setString(2, password);
                ps2.setString(3, nickname);
                ps2.setInt(4, age);
                // 执行DML
                int i = ps2.executeUpdate();
                System.out.println("恭喜你,注册成功");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}














